package com.manlost.upload.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.io.IOUtils;
import org.springframework.util.StringUtils;

import com.alibaba.simpleimage.ImageFormat;
import com.alibaba.simpleimage.ImageRender;
import com.alibaba.simpleimage.SimpleImageException;
import com.alibaba.simpleimage.render.ReadRender;
import com.alibaba.simpleimage.render.ScaleParameter;
import com.alibaba.simpleimage.render.ScaleParameter.Algorithm;
import com.alibaba.simpleimage.render.ScaleRender;
import com.alibaba.simpleimage.render.WriteParameter;
import com.alibaba.simpleimage.render.WriteRender;

/**
 * @author: HuJianbo (hujianbo88@sohu.com)
 * @date: 2012-4-1
 * @description:
 */
public class ThumbnailUtil {

    /**
     * 生成缩略图
     */
    public static void generateThumbnail(String picPath, String destPath, int pixNumber) {
        if (StringUtils.hasText(picPath)) {
            File in = new File(picPath); // 原图片
            if (in.exists()) {
                String picName = getPictureNameFromPath(picPath);
                String newName = generateThumbnailName(picName, pixNumber);
                System.out.println(destPath + File.separator + newName);
                File out = new File(destPath + File.separator + newName); // 目的图片
                ScaleParameter scaleParam = new ScaleParameter(pixNumber, pixNumber, Algorithm.AUTO); // 将图像缩略到1024x1024以内，不足1024x1024则不做任何处理
                WriteParameter writeParam = new WriteParameter(); // 输出参数，默认输出格式为JPEG

                FileInputStream inStream = null;
                FileOutputStream outStream = null;
                ImageRender wr = null;
                try {
                    inStream = new FileInputStream(in);
                    outStream = new FileOutputStream(out);
                    ImageRender rr = new ReadRender(inStream);
                    ImageRender sr = new ScaleRender(rr, scaleParam);
                    wr = new WriteRender(sr, outStream, ImageFormat.JPEG, writeParam);

                    wr.render(); // 触发图像处理
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    IOUtils.closeQuietly(inStream); // 图片文件输入输出流必须记得关闭
                    IOUtils.closeQuietly(outStream);
                    if (wr != null) {
                        try {
                            wr.dispose(); // 释放simpleImage的内部资源
                        } catch (SimpleImageException ignore) // TODO SimpleImageException
                        {

                        }
                    }
                }
            }
        }

    }

    /**
     * get the picture name (like: xxx.jpg) from the picture path
     * 
     * @param path
     * @return String
     */
    public static String getPictureNameFromPath(String path) {
        String pictureName = null;
        int index1 = -1;
        int index2 = -1;
        int index = -1;
        if (StringUtils.hasText(path)) {
            index1 = path.lastIndexOf("/");
            index2 = path.lastIndexOf("\\");
            if (index1 > -1 || index2 > -1) {
                index = max(index1, index2);
                pictureName = path.substring(index + 1);
            }

            // 传入的为图片名，如 468.jpg
            if (index1 == -1 && index2 == -1 && path.indexOf(".") > -1) {
                return path;
            }
        }
        return pictureName;
    }

    /**
     * get the thumbnail picture name
     * 
     * @param oldName
     * @param pix
     * @return
     */
    public static String generateThumbnailName(String oldName, int pix) {
        int index = oldName.indexOf(".");
        Long picId = generateID4Thumbnail();
        StringBuffer newName = new StringBuffer();
        newName.append(picId).append("-").append(pix).append(oldName.substring(index));
        return newName.toString();
    }

    /**
     * get the max number of tow numbers
     * 
     * @param a
     * @param b
     * @return int
     */
    public static int max(int a, int b) {
        if (a >= b) return a;
        else return b;
    }

    public static Long generateID4Thumbnail() {
        Date currentTime = new Date();
        String id = dateToStr(currentTime, "yyyyMMddHHmmssSSS") + genRandomNum(2);
        return Long.valueOf(id);
    }

    public static String genRandomNum(int length) {
        int index = 0;
        StringBuffer str = new StringBuffer("");
        for (; index < length; index++) {
            str.append((int) (Math.random() * 10));
        }
        return str.toString();
    }

    public static Long generatePictureID() {
        Date currentTime = new Date();
        StringBuffer sb = new StringBuffer();
        String str = dateToStr(currentTime, "yyyyMMddHHmmssSSS");
        sb.append(str);
        int random = (int) (Math.random() * 90) + 10;
        sb.append(random);
        return new Long(sb.toString());
    }

    public static String dateToStr(Date date, String format) {
        if (date == null) return "";
        SimpleDateFormat df = new SimpleDateFormat(format);
        return df.format(date);
    }

}
